package com.project.demo.controller;

import cn.hutool.core.io.IoUtil;
import com.je.core.base.AbstractPlatformController;
import com.je.core.controller.PlatformController;
import com.je.core.exception.PlatformException;
import com.je.core.exception.PlatformExceptionEnum;
import com.je.core.util.SecurityUserHolder;
import com.je.paas.document.model.bean.FileUpload;
import com.je.paas.document.model.bo.FileBO;
import com.je.paas.document.service.DocumentBusService;
import com.je.rbac.model.EndUser;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.wordwriter.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Word Template Demo
 *
 * @ProjectName: jepaas-commercial
 * @Package: com.project.demo.controller
 * @ClassName: WordTemplateDemoController
 * @Description: java类作用描述
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2019</p>
 */
@Controller
@RequestMapping(value = "/word")
public class WordTemplateDemoController extends AbstractPlatformController {

    @Autowired
    private DocumentBusService documentBusService;

    @RequestMapping(value = {"/genWordFromTemplate"},produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public String genWordFromTemplate(HttpServletRequest request){
        EndUser currentUser = SecurityUserHolder.getCurrentUser();
        String userName = request.getParameter("userName");
        String userCode = request.getParameter("userCode");
        String userImage = request.getParameter("userImage");
        String template = request.getParameter("template");
        String id = request.getParameter("id");
        String fileKey = template.substring(template.lastIndexOf("*")+1);
        String userImageFileKey = userImage.substring(userImage.lastIndexOf("*")+1);

        PageOfficeCtrl poCtrl1 = new PageOfficeCtrl(request);
        poCtrl1.setServerPage(request.getContextPath()+"/poserver.zz"); //此行必须

        WordDocument document = new WordDocument();
        DataRegion userNameRegion = document.openDataRegion("PO_USERNAME");
        DataRegion userCodeRegion = document.openDataRegion("PO_USERCODE");
        DataRegion userImageRegion = document.openDataRegion("PO_USERIMAGE");
        userNameRegion.setValue(userName);
        userCodeRegion.setValue(userCode);
        userImageRegion.setValue(String.format("[image]/je/document/preview?fileKey=%s[/image]",userImageFileKey));
        poCtrl1.setWriter(document);
        poCtrl1.setSaveFilePage("/word/savefile?path=" + fileKey + "&id=" + id);
        poCtrl1.webOpen("/word/readfile?filePath=" + fileKey, OpenModeType.docRevisionOnly, currentUser.getUsername());
        return poCtrl1.getHtmlCode("PageOfficeCtrl1");
    }

    @RequestMapping({"/savefile"})
    public void savefile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        EndUser currentUser = SecurityUserHolder.getCurrentUser();
        FileSaver fs = new FileSaver(request, response);
        InputStream in = fs.getFileStream();
        String id = request.getParameter("id");
        String fileName = "生成文件.docx";
        FileUpload uploadFile = new FileUpload(fileName, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Long.valueOf(in.available()), in);
        FileBO fileBO = documentBusService.saveSingleFile(uploadFile,currentUser.getUserId());
        String filePath = String.format("%s*%s",fileName,fileBO.getFileKey());
        metaService.executeSql("UPDATE PAGEOFFICE_TEST SET TEST_SCWJ='{0}' where PAGEOFFICE_TEST_ID='{1}'",filePath,id);
        fs.close();
    }

    @RequestMapping({"/readfile"})
    public void readfile(HttpServletRequest request, HttpServletResponse response) {
        String filePath = request.getParameter("filePath");
        if (!StringUtils.isBlank(filePath)) {
            try {
                FileBO fileBO = documentBusService.readFile(filePath);
                InputStream is = fileBO.getFile();
                response.setContentType("application/octet-stream");
                OutputStream toClient = response.getOutputStream();
                IoUtil.copy(is, toClient);
                IoUtil.close(is);
                toClient.flush();
                toClient.close();
            } catch (Exception var6) {
                var6.printStackTrace();
                throw new PlatformException("读取文件失败", PlatformExceptionEnum.UNKOWN_ERROR, request, var6);
            }
        } else {
            throw new PlatformException("非法参数", PlatformExceptionEnum.UNKOWN_ERROR);
        }
    }


}
